package cn.yx.common.jdbc.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * <p>DataSource数据源服务，在SpringBoot环境下，直接获取数据源和从数据源获取连接</p>
 *
 * @author Wgssmart
 */
@Component
@Slf4j
public class DataSourceService {

    private final DataSource dataSource;

    public DataSourceService(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    /**
     * 返回数据源
     *
     * @return
     */
    public DataSource getDataSource() {
        return dataSource;
    }

    /**
     * 从数据源中获取Connection连接，如果出现异常，则返回null
     *
     * @return
     */
    public Connection getConnection() {
        try {
            return dataSource.getConnection();
        } catch (SQLException e) {
            log.error("get connection from data source error: {}", e.getMessage());
            return null;
        }
    }
}
